package com.sunny.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;

public class AioFile {

    private static final int MAX = 1024;

    public static void main(String[] args) {


//        Path path = Paths.get("aaa");
//        File file = path.toFile();
//        try {
//            FileInputStream fis = new FileInputStream(file);
//            InputStreamReader inputStreamReader = new InputStreamReader(fis,"UTF-8");
//            int c;
//            while ((c=inputStreamReader.read())!=-1){
//                System.out.print((char)c);
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        try {
            Path path = Paths.get("aaa");

            AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path);
            ByteBuffer buffer = ByteBuffer.allocate(MAX);
            fileChannel.read(buffer, 0, fileChannel, new CompletionHandler<Integer, AsynchronousFileChannel>() {
                @Override
                public void completed(Integer result, AsynchronousFileChannel attachment) {
                    if(result != -1){
                        buffer.flip();
                        String res = new String(buffer.array());
                        System.out.println(res);
                        buffer.clear();
                    }else {
                        System.out.println("读取完毕");
                    }
                    System.out.println("读取结果为："+result);
                }

                @Override
                public void failed(Throwable exc, AsynchronousFileChannel attachment) {
                    System.out.println("请求有误");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
